﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibrary.Net.Ndmp
{
    /// <summary>
    /// Holds and manages request of NDM protocol.
    /// </summary>
    public sealed class Request : IParsable, IBuildable
    {
        /// <summary>
        /// Gets or sets the command.
        /// </summary>
        /// <value>
        /// The command.
        /// </value>
        public NdmpCommand Command { get; set; }

        /// <summary>
        /// Gets or sets the data.
        /// </summary>
        /// <value>
        /// The data.
        /// </value>
        public string Data { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        public Request()
        {
            this.Command = NdmpCommand.Unknown;
            this.Data = "";
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class with specified command and data.
        /// </summary>
        /// <param name="Command">The command.</param>
        /// <param name="Property">The property/data.</param>
        public Request(NdmpCommand Command, string Property)
        {
            this.Command = Command;
            this.Data = Property;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return String.Format("{0}\r\n{1}\r\nDO\r\n", NCManager.ToString(this.Command), this.Data);
        }

        /// <summary>
        /// Parses string into current object.
        /// </summary>
        /// <param name="input">Specifies string which has to be parsed.</param>
        void IParsable.Parse(string input)
        {
            Match m = Regex.Match(input, "(SELECT|PUT|DELETE|UPDATE|UNKNOWN)\\r\\n(.*)\\r\\nDO\\r\\n", RegexOptions.Singleline);
            if(!m.Success)
                throw new Exception("Invalid request input passed for parsing.");
            else
            {
                this.Command = NCManager.ToCommand(m.Groups[1].Value);
                this.Data = m.Groups[2].Value;
            }
        }

        /// <summary>
        /// Builds object into string.
        /// </summary>
        /// <returns>
        /// Built string.
        /// </returns>
        string IBuildable.Build()
        {
            return this.ToString();
        }
    }
}